#usr/bin/python
# -*- coding: utf-8 -*-


# self implementation generated from reading ui file 'main.ui'
#
# Created: Sun May 30 17:07:18 2010
#	  by: PyQt4 UI code generator 4.7.2
#
# WARNING! All changes made in this file will be lost!



#LICENSE
#
#Copyright: Marc Dubois
#contributors: Pierre Millard, Fabien Jourdan, Ludovic Cottret
#Fabien Letisse
#
#m_dubois@insa-toulouse.fr
#
#This software is a computer program whose purpose is to treat data 
#from Mass Spectrometry.
#
#This software is governed by the CeCILL license under French law and
#abiding by the rules of distribution of free software.  You can  use, 
#modify and/ or redistribute the software under the terms of the CeCILL
#license as circulated by CEA, CNRS and INRIA at the following URL
#"http://www.cecill.info". 
#
#As a counterpart to the access to the source code and  rights to copy,
#modify and redistribute granted by the license, users are provided only
#with a limited warranty  and the software's author,  the holder of the
#economic rights,  and the successive licensors  have only  limited
#liability. 
#
#In this respect, the user's attention is drawn to the risks associated
#with loading,  using,  modifying and/or developing or reproducing the
#software by the user in light of its specific status of free software,
#that may mean  that it is complicated to manipulate,  and  that  also
#therefore means  that it is reserved for developers  and  experienced
#professionals having in-depth computer knowledge. Users are therefore
#encouraged to load and test the software's suitability as regards their
#requirements in conditions enabling the security of their systems and/or 
#data to be ensured and,  more generally, to use and operate it in the 
#same conditions as regards security. 
#
#The fact that you are presently reading this means that you have had
#knowledge of the CeCILL license and that you accept its terms.


from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
import sys
import os.path as path


class Main_Window(QtGui.QMainWindow):
	"""
	Gui of the main window
	"""
	def __init__(self):
		
		"""
		Constructor with all the models needed
		setup menus
		"""
		QtGui.QMainWindow.__init__(self)
		
		#treeview 1
		self.spectr_model =  QtGui.QStandardItemModel ()
		self.spectr_model.setHorizontalHeaderLabels(["Spectra Visualisation"])
		self.chrom_model =  QtGui.QStandardItemModel ()
		self.chrom_model.setHorizontalHeaderLabels(["Chromatograms Visualisation"])

		#treeview2
		self.peak_model = QtGui.QStandardItemModel ()
		self.peak_model.setHorizontalHeaderLabels(["Peaks Visualisation (trans/rt)"])
	
		#treeview3
		self.clust_model =QtGui.QStandardItemModel()
		self.clust_model.setHorizontalHeaderLabels(["Cluster Visualisation (trans/rt)"])
		
		self.setupUi()
		#tree 1 actions
		
		self.treeView_actions=[]
		self.treeView_menu = QtGui.QMenu(self.treeView)
		erase_= QtGui.QAction("erase item", self)
		erase_icon=QtGui.QIcon(QtGui.QPixmap("gui\\icons\\delete.png"))
		erase_.setIcon(erase_icon)
		self.treeView_menu.addAction(erase_)
		self.treeView_actions.append(erase_)
		self.treeView_menu.addSeparator()
		self.treeView_actions.append(self.treeView_menu.addAction("multiple plot"))
		self.treeView_actions.append(self.treeView_menu.addAction("correlation plot"))
		#submenu
		self.treeView_actions.append(self.treeView_menu.addAction("Show in 3D"))
		self.treeView_actions.append(self.treeView_menu.addAction("spectrogram plot"))
		self.treeView_actions.append(self.treeView_menu.addAction("cytoscape web"))

		
		self.mdi_actions =[]
		self.mdi_menu = QtGui.QMenu(self.mdiArea)
		self.mdi_actions.append(self.mdi_menu.addAction("Cascade View "))
		self.mdi_actions.append(self.mdi_menu.addAction("Tile View"))
		
		#file menu_actions
		self.lst_file_actions=[]
		self.lst_algo_actions=[]
		self.lst_id_actions=[]
		self.lst_view_actions=[]
		self.lst_stats_actions=[]
		self.lst_tools_actions=[]
		self.lst_about_actions=[]
		self.setupMenus()
		
		
	
	def setupMenus(self):
		
		"""
		setup Menus
		called in the constructor
		"""


		self.file_menu = QtGui.QMenu('&File')
		#first file menu
		#open 0
		open_=QtGui.QAction("&Open rawfile", self)
		open_.setShortcut(QtGui.QKeySequence(Qt.CTRL + Qt.Key_O))
		open_icon=QtGui.QIcon(QtGui.QPixmap(path.normcase("gui/icons/open.png")))
		open_.setIcon(open_icon)
		self.file_menu.addAction(open_)
		self.lst_file_actions.append(open_)
		#merge 1
		self.lst_file_actions.append(self.file_menu.addAction("&Merge files or peaklist"))
		#peaklist 2
		self.lst_file_actions.append(self.file_menu.addAction("Open peaklist"))
		#convert 3
		convert_=QtGui.QAction("Convert...", self)
		convert_icon=QtGui.QIcon(QtGui.QPixmap(path.normcase("gui/icons/convert.png")))
		convert_.setIcon(convert_icon)
		self.file_menu.addAction(convert_)
		self.lst_file_actions.append(convert_)
		
		self.file_menu.addSeparator()
		
		#exit 4
		exit_action =QtGui.QAction("Exit", self)
		exit_action.setShortcut(QtGui.QKeySequence(Qt.CTRL + Qt.Key_Q))
		self.file_menu.addAction(exit_action)
		self.lst_file_actions.append(exit_action)
		
		#adding the menu
		self.menuBar().addMenu(self.file_menu)
		
		self.view_menu =QtGui.QMenu("View")
		#checkable dock ???
		self.view_menu.addAction("Cascade View",self.switchMdiView2, QtGui.QKeySequence(Qt.CTRL + Qt.Key_N))
		self.view_menu.addAction("Title View", self.switchMdiView, QtGui.QKeySequence(Qt.CTRL + Qt.Key_T))
		self.view_menu.addAction("Change view Mode",  self.updateViewMode,   QtGui.QKeySequence(Qt.CTRL + Qt.Key_B))
		self.sub_plot_ =QtGui.QMenu("Plotting...")
		self.lst_view_actions.append(self.sub_plot_.addAction("3D Plot"))
		self.lst_view_actions.append(self.sub_plot_.addAction("Cytoscape web"))
		self.lst_view_actions.append(self.sub_plot_.addAction("Spectrogram Plot"))
		self.view_menu.addMenu(self.sub_plot_)
		
		self.menuBar().addMenu(self.view_menu)


		self.algo_menu= QtGui.QMenu("Algorithm")
		#peak picking 0
		peak_ = QtGui.QAction("Peack Picking", self)
		peak_.setShortcut(QtGui.QKeySequence(Qt.CTRL + Qt.Key_P))
		peak_icon=QtGui.QIcon(QtGui.QPixmap("gui\\icons\\pickedpeakicon.png"))
		peak_.setIcon(peak_icon)
		self.algo_menu.addAction(peak_)
		self.lst_algo_actions.append(peak_)
		
		
		clust_ =  QtGui.QAction("Clustering", self)
		clust_.setShortcut(QtGui.QKeySequence(Qt.CTRL + Qt.Key_L))
		clust_icon=QtGui.QIcon(QtGui.QPixmap("gui\\icons\\cluster.png"))
		clust_.setIcon(clust_icon)
		self.algo_menu.addAction(clust_)
		self.lst_algo_actions.append(clust_)
		
		
		# deisotoping 1
		#****************************************
		deiso_ = QtGui.QAction("Deisotoping", self)
		deiso_.setShortcut(QtGui.QKeySequence(Qt.CTRL + Qt.Key_D))
		self.algo_menu.addAction(deiso_)
		self.lst_algo_actions.append(deiso_)
		#cut off 2
		cut_ =  QtGui.QAction("Apply cut_off", self)
		cut_.setShortcut(QtGui.QKeySequence(Qt.CTRL + Qt.Key_M))
		self.algo_menu.addAction(cut_)
		self.lst_algo_actions.append(cut_)
		#*****************************************
		#clustering 3
		self.menuBar().addMenu(self.algo_menu)
		
		#identification 0
		self.id_menu =QtGui.QMenu("Identification")
		id_ =  QtGui.QAction("Metabolites", self)
		id_.setShortcut(QtGui.QKeySequence(Qt.CTRL + Qt.Key_I))
		self.id_menu.addAction(id_)
		self.lst_id_actions.append(id_)
		self.menuBar().addMenu(self.id_menu)
		
		
		self.stat_menu= QtGui.QMenu("Statistics")
		self.menuBar().addMenu(self.stat_menu)
		
		self.tools_menu =QtGui.QMenu("Tools")
		web =  QtGui.QAction("Web Browser", self)
		self.tools_menu.addAction(web)
		self.lst_tools_actions.append(web)
		cyto =  QtGui.QAction("cytoscape", self)
		cyto_icon =QtGui.QIcon(QtGui.QPixmap(path.normcase("gui/icons/cytoscape.jpeg")))
		cyto.setIcon(cyto_icon)
		self.lst_tools_actions.append(self.tools_menu.addAction(cyto))
		editor = QtGui.QAction("Editor", self)
		self.lst_tools_actions.append(self.tools_menu.addAction(editor))
		self.menuBar().addMenu(self.tools_menu)
		
		
		
		self.about_menu= QtGui.QMenu("About")
		pyqt =  QtGui.QAction("PyQt4", self)
		pyqt_icon =QtGui.QIcon(QtGui.QPixmap(path.normcase("gui/icons/logo_QT4.png")))
		pyqt.setIcon(pyqt_icon)
		self.lst_about_actions.append(pyqt)
		self.about_menu.addAction(pyqt)
		metms =  QtGui.QAction("MetMS Documentation", self)
		metms_icon =QtGui.QIcon(QtGui.QPixmap(path.normcase("gui/icons/logo.png")))
		metms.setIcon(metms_icon)
		self.lst_about_actions.append(metms)
		self.about_menu.addAction(metms)
		
		self.menuBar().addMenu(self.about_menu)
		

		
		
	def setupUi(self):
		"""
		Make the GUI
		"""
		
		self.resize(1000, 700)
		
		self.mdiArea = QtGui.QMdiArea(self)
		#self.mdiArea.setBackground(QtGui.QBrush(QtGui.QImage("gui/logo_Qt4.png")))
		
		self.mdiArea.setBackground(QtGui.QBrush(QtGui.QColor(Qt.darkGray)))
		self.setCentralWidget(self.mdiArea)
		
		self.dockWidget = QtGui.QDockWidget(self)
		self.dockWidget.setFloating(0)
		self.dockWidget.setWindowTitle("Controller")

		self.tool_box= QtGui.QToolBox(self)
		
		self.tabWidget = QtGui.QTabWidget(self)
		font = QtGui.QFont()
		font.setPointSize(9)
		self.tabWidget.setFont(font)
		
		
		self.tab = QtGui.QWidget()

		self.verticalLayout_3 = QtGui.QVBoxLayout(self.tab)
		self.treeView = QtGui.QTreeView(self.tab)
		self.treeView.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
		
		self.verticalLayout_3.addWidget(self.treeView)
		self.pushButton = QtGui.QPushButton(self.tab)
		self.verticalLayout_3.addWidget(self.pushButton)
		self.tabWidget.addTab(self.tab, "")
		self.tab_2 = QtGui.QWidget()

		self.verticalLayout_4 = QtGui.QVBoxLayout(self.tab_2)
		self.treeView_2 = QtGui.QTreeView(self.tab_2)
		self.verticalLayout_4.addWidget(self.treeView_2)
		self.tabWidget.addTab(self.tab_2, "")
		self.tab_3 = QtGui.QWidget()

		self.verticalLayout_5 = QtGui.QVBoxLayout(self.tab_3)
		self.treeView_3 = QtGui.QTreeView(self.tab_3)
		self.verticalLayout_5.addWidget(self.treeView_3)
		self.tabWidget.addTab(self.tab_3, "")
		self.tabWidget.setCurrentIndex(0)
	
		self.tool_box.addItem(self.tabWidget,  "Visualisation")
		self.tool_box.addItem(QtGui.QTreeView(self),  "Annotation")
		self.tool_box.addItem(QtGui.QTableView(self),  "Data View")
		self.dockWidget.setWidget(self.tool_box)

		self.addDockWidget(Qt.DockWidgetArea(0x1),self.dockWidget)
	
		self.pb =QtGui.QProgressBar()
		self.statusBar().addPermanentWidget(self.pb)
		
		
		self.retranslateUi()
		QtCore.QMetaObject.connectSlotsByName(self)

	def retranslateUi(self):
		"""Needed for retranslation, not supposed to be used except for translation"""
		
		self.setWindowTitle(QtGui.QApplication.translate("self", "pySpec", None, QtGui.QApplication.UnicodeUTF8))
		self.pushButton.setText(QtGui.QApplication.translate("self", "Switch View", None, QtGui.QApplication.UnicodeUTF8))
		self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate("self", "Visualisation", None, QtGui.QApplication.UnicodeUTF8))
		self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QtGui.QApplication.translate("self", "Peaks List", None, QtGui.QApplication.UnicodeUTF8))
		self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), QtGui.QApplication.translate("self", "Clusters", None, QtGui.QApplication.UnicodeUTF8))

	
	def MakingMenu(self,point):
		"""Making menu in the mdi Area for switching view"""
		
		menu=QtGui.QMenu(self.mdiArea)
		menu.addAction("tile arrangement", self.switchMdiView, QtGui.QKeySequence(Qt.CTRL + Qt.Key_T))
		menu.addAction("Cascade arrangement", self.switchMdiView2, QtGui.QKeySequence(Qt.CTRL + Qt.Key_N))
		menu.exec_(QtGui.QCursor.pos())
		
	###MDI UPDATE	
	def switchMdiView(self):
		"""Switch mdi View"""
		self.mdiArea.tileSubWindows()
		
	def switchMdiView2(self):
		"""Switch mdi View"""
		
		self.mdiArea.cascadeSubWindows()
		
	def switchMdiView3(self):
		"""
		Switch mdi View
		"""
		
		if self.mdiArea.viewMode() == QtGui.QMdiArea.SubWindowView:
			self.mdiArea.setViewMode(QtGui.QMdiArea.TabbedView)
		else:
			self.mdiArea.setViewMode(QtGui.QMdiArea.SubWindowView)
	
	def addMdiSubWindow(self, plot, title=""):#
		""" 
		Allow addition of new window in the mdiarea
		"""
		
		#plot.show()
		win = QtGui.QMdiSubWindow(self.mdiArea)#mdiArea
		plot.setParent(win)
		win.setWindowTitle (title)
		win.setWidget(plot)
		win.show()
		##################
		#self.mdiArea.addSubWindow(win)
		return win
		
		
	
######TREE VIEW UPDATE move to dock_widget_control ???
	def updateTreeView(self):
		"""Tree View update switch spectre/chromato"""
		if self.treeView.model() == self.spectr_model:
			self.treeView.setModel( self.chrom_model )
		else:
			self.treeView.setModel( self.spectr_model)
			
	def addTreeViewModel (self,model1, model2):
		"""Add a model """
		
		self.chrom_model.appendRow(model1)
		self.spectr_model.appendRow(model2)
	

	
	def showCustomContextMenu(self, pos):
		"""
		Allow to show context menu
		"""
		self.initialize_menu_actions()

		if self.tabWidget.currentIndex() == 0:
			try:
				last_index = self.treeView.selectedIndexes()[-1]
			except:
				self.ShowErrorMessage("Error index", "Error index outlines")
			if self.chrom_model.itemFromIndex(last_index).parent():# or self.spectr_model.itemFromIndex(index).parent():
				self.treeView_actions[0].setEnabled(False)
			else:
				self.treeView_actions[0].setEnabled(True)
			self.treeView_actions[2].setEnabled(False)


		elif self.tabWidget.currentIndex() == 1:
			index = self.treeView_2.selectedIndexes()[-1]
			if self.peak_model.itemFromIndex(index).parent():# or self.spectr_model.itemFromIndex(index).parent():
				self.treeView_actions[0].setEnabled(False)
			else:
				self.treeView_actions[0].setEnabled(True)
			self.treeView_actions[1].setEnabled(False)
		
		else:
			index = self.treeView_3.selectedIndexes()[-1]
			if self.clust_model.itemFromIndex(index).parent():# or self.spectr_model.itemFromIndex(index).parent():
				self.treeView_actions[0].setEnabled(False)
			else:
				self.treeView_actions[0].setEnabled(True)
			self.treeView_actions[1].setEnabled(False)
			self.treeView_actions[2].setEnabled(False)
				
		self.treeView_menu.exec_(QtGui.QCursor.pos())
	
	
	
	def initialize_menu_actions(self):
		for action in self.treeView_actions:
			action.setEnabled(True)
	
	def MakingMenu(self, pos):
		"""
		Show contextMenu in the mdi Area
		"""
		self.mdi_menu.exec_(QtGui.QCursor.pos())
	
	def visibleDock(self):
		"""DO NOT WORK"""
		if self.dockWidget.isVisible():
			self.dockWidget.setVisible(1)
		else:
			self.dockWidget.setVisible(0)
	
	#move to mdi_area_control
	def updateViewMode(self):
		if self.mdiArea.ViewMode( ) ==1:
			self.mdiArea.setViewMode(0)
		elif self.mdiArea.ViewMode( ) ==0:
			self.mdiArea.setViewMode(1)
		

######HANDLING ERRORS
	def ShowErrorMessage(self, title, string):
		QtGui.QMessageBox.critical(self, title, string, 0, 0)
	
	def ShowWarningMessage(self, title, string):
		QtGui.QMessageBox.warning(self, title, string, QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
	
	def ShowInformationMessage(self, title, string):
		QtGui.QMessageBox.information(self, title, string, 0)
		
#######ProgressBar Handling
	def update_progress_bar(self, i):
		"""update the value of the progress bar for all the treatment"""
		self.pb.setValue(i)

	def to_indetermined_mode(self):
		self.pb.setMaximum(0)
		
	def to_determined_mode(self):
		self.pb.setMaximum(100)
		
		

#######StatusBar Handling
	def ShowInStatusBar(self, string, time=5000):
		self.statusBar().showMessage(string, time)
		
		
####MAIN Test
if __name__=="__main__":
	app = QtGui.QApplication(sys.argv)
	splash = QtGui.QSplashScreen (QtGui.QPixmap ("pingouins.jpg"), Qt.WindowStaysOnTopHint)
	splash.showMessage((u'STARTING NOW...'), Qt.AlignCenter | Qt.AlignBottom, Qt.black)
	app.processEvents()
	splash.show()
	window =Main_Window()
	window.show()
	splash.finish(window)
	app.exec_()
